<template>
    <div class="app-container" v-loading="loading">
        <div class="container" >
      <el-form ref="searchForm" :model="searchForm" inline>
        <el-form-item label="组织一级" v-if="this.$store.state.user.level <= 1"> 
          <el-select
            v-model="searchForm.userId"
            clearable
            filterable
            placeholder="请选择"
            :disabled="showOneLevel"
            @change="selectChange(1)"
          >
            <el-option
              v-for="item in oneLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织二级" v-if="this.$store.state.user.level <= 2">
          <el-select
            v-model="searchForm.twoUserId"
            filterable
            clearable
            placeholder="请选择"
            :disabled="showTwoLevel"                                                                                                                                                                                                                                                                                                                                                                                         
            @change="selectChange(2)"
          >
            <el-option
              v-for="item in twoLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织三级" v-if="this.$store.state.user.level <= 3">
          <el-select
            v-model="searchForm.threeUserId"
            filterable
            clearable
            placeholder="请选择"
            :disabled="showThreeLevel"
            @change="selectChange(3)"
          >
            <el-option
              v-for="item in threeLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织四级" v-if="this.$store.state.user.level <= 4">
          <el-select
            v-model="searchForm.fourUserId"
            filterable
            clearable
            placeholder="请选择"
            :disabled="showFourLevel"
            @change="selectChange(4)"
          >
            <el-option
              v-for="item in fourLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织五级" v-if="this.$store.state.user.level <= 5">
          <el-select
            v-model="searchForm.fiveUserId"
            filterable
            clearable
            placeholder="请选择"
            :disabled="showFiveLevel"
            @change="selectChange(5)"
          >
            <el-option
              v-for="item in fiveLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织六级" v-if="this.$store.state.user.level <= 6">
          <el-select
            v-model="searchForm.sixUserId"
            filterable
            clearable
            placeholder="请选择"
            :disabled="showSixLevel"
            @change="selectChange(6)"
          >
            <el-option
              v-for="item in sixLevelUserInfoList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

          <el-form-item label="起止时间:" >
              <el-date-picker
                v-model='searchForm.dateTime'
                type='datetimerange'
                :picker-options='pickerOptions'
                range-separator='至'
                start-placeholder='开始日期'
                end-placeholder='结束日期'
                align='right'
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable>
              </el-date-picker>
          </el-form-item>
          <el-form-item label="维度:" >
            <el-select
              v-model="searchForm.dimension"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in timeDimensionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 展示 子用户的 或者当前用户的 或者当前用户加当前用户子用户s的 -->
          <!-- todos：根据需求看是否提供一个按钮供选择 -->
  
  
  
  
          <el-form-item>
                <el-button
                    style="margin-left:5px;background:#5B6BF4;font-family:'HarmonyOS_Sans_SC_Regular';border:none"
                    type="primary" icon="el-icon-search" size="mini" @click="queryByForm">检索</el-button>
            </el-form-item>
        <el-form-item>
          <!-- <ExportExcel :list="exportList" :tHeader="tHeader" :tValue="tValue" filename="KPI-人员" buttonName="数据导出"></ExportExcel> -->
        </el-form-item>
      </el-form>
  
      <el-table ref="deviceTable" :data="devicesData" style="width: 100%" @selection-change="handleSelectionChange()"  row-key="id">
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
          >
        </el-table-column>
        <el-table-column label="日期" prop="date" align="center"></el-table-column>
        <el-table-column label="业代姓名" prop="user.nickname" align="center"></el-table-column>
        <el-table-column label="店铺数" prop="storeNum" align="center"></el-table-column>
        <el-table-column label="有冰柜的店铺数" prop="storeDeviceNum" align="center"></el-table-column>
        <el-table-column label="冰柜正常的店铺数" prop="normalStoreNum" align="center"></el-table-column>
        <el-table-column label="冰柜异常的店铺数" prop="abnormalStoreNum" align="center"></el-table-column>
        <el-table-column label="运营中的冰柜数" prop="deviceCount" align="center"></el-table-column>
        <el-table-column label="通电冰柜数" prop="powerDeviceNum" align="center"></el-table-column>
        <el-table-column label="失联冰柜数" prop="missingDeviceNum" align="center"></el-table-column>
        <el-table-column label="低功耗冰柜数" prop="lowPowerDeviceNum" align="center"></el-table-column>
        <el-table-column label="正常冰柜数" prop="normalDeviceNum" align="center"></el-table-column>
        <el-table-column label="异常冰柜数" prop="abnormalDeviceNum" align="center"></el-table-column>
        <el-table-column label="位置异常冰柜数" prop="locationAbnormalDeviceNum" align="center"></el-table-column>
        <el-table-column label="温度异常冰柜数" prop="tempAbnormalDeviceNum" align="center"></el-table-column>
        <el-table-column label="图片异常冰柜数" prop="sieveAbnormalDeviceNum" align="center"></el-table-column>
        <el-table-column label="业代拜访数" prop="businessVisitNum" align="center"></el-table-column>
        <el-table-column label="平均纯净度（空）" prop="purityEmptyAvg" align="center"></el-table-column>
        <el-table-column label="平均纯净度" prop="purityAvg" align="center"></el-table-column>
      </el-table>
      <!-- <div class="page">
            <div style="margin-right: 20px;color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">共7条</div>
            <el-button type="text" style="color:#333;margin-right: 10px;"><</el-button>
                    <div class="pageborder">1</div>
                    <el-button type="text" style="color:#333;margin-right: 10px;">></el-button>
                    <div style="margin-right: 10px;color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">前往</div>
                    <el-input type="number" style="width: 60px;margin-right: 10px;" :min="0" v-model="pageIndex" />
                    <div style="color: #333;font-family:'HarmonyOS_Sans_SC_Regular'">页</div>
            </div> -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 50, 100,200,500,1000,2000,3000]"
        @pagination="pagination"
      />
    </div>
    </div>
  </template>
  
  <script>
  //import ExportExcel from '../../../components/ExcelUtils/Export2Excel.vue'
  // import { userListSon,userListPageAll } from '@/api/user'
  // import {getKpiUser,getFirstCoverDisplayByText} from '@/api/dataCenter'
  // import initCust from '@/plugins/mixin'
  // import AllAddress from '@/plugins/data.js'
  const emumStatus = {
    ONLINE: '在线',
    OFFLINE: '离线',
    UNACTIVE: '设备未激活',
    UNKNOWN: '未知',
    DISABLE: '已禁用',
  }
  export default {
    // mixins: [initCust],
    // components: {
    //   ExportExcel
    // },
    data() {
      return {
        devicesData:[],//表格数据
        pageIndex:1,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        exportList: [],
        tHeader: ['日期','业代姓名','店铺数','有冰柜的店铺数','冰柜正常的店铺数','冰柜异常的店铺数', 	'通电冰柜数'	,'失联冰柜数',	'低功耗冰柜数','正常冰柜数','异常冰柜数',	'位置异常冰柜数',	'温度异常冰柜数',	'图片异常冰柜数',	'业代拜访数',	'平均纯净度（含空位）','平均纯净度（不含空位）'],
        tValue: ['date','nickname','storeNum','storeDeviceNum','normalStoreNum','normalStoreNum','powerDeviceNum','missingDeviceNum','lowPowerDeviceNum', 'normalDeviceNum','abnormalDeviceNum','locationAbnormalDeviceNum','tempAbnormalDeviceNum','sieveAbnormalDeviceNum'
                  ,'businessVisitNum','purityEmptyAvg','purityAvg'],
        oHeader: ['产品编号','cpuid','资产编号'],
        oValue:['123','123','123'],
        // 用户相关
        oneLevelUserInfoList:[],
        twoLevelUserInfoList:[],
        threeLevelUserInfoList:[],
        fourLevelUserInfoList:[],
        fiveLevelUserInfoList:[],
        sixLevelUserInfoList:[],
        paramId:'',
        showOneLevel:true,
        showTwoLevel:true,
        showThreeLevel:true,
        showFourLevel:true,
        showFiveLevel:true,
        showSixLevel:true,
        // 分页相关数据
        total: 0,
        pageNum: 1,
        pageSize: 20,
        timeDimensionList:[
            {
                          value: 1,
                          label:'日'
                      },
            {
                          value:2,
                          label:'周'
                      },
            {
                          value:3,
                          label:'月'
                      },
                      {
                          value:4,
                          label:'季度'
                      }
        ],
        loading: false,
        searchForm: {
          dateTime:'',
          startDate:'',//开始日期,格式: 2023-02-20
          endDate:'', //结束日期,格式: 2023-02-20
          dimension: 1, // 时间维度（日/周/月/季度）日：1，周：2，月：3，季度:4
          userId:'',  //用户id
          twoUserId:'',
          threeUserId:'',
          fourUserId:'',
          fiveUserId:'',
          sixUserId:'',
        }
      }
    },
    created(){
      //this.getUserListInfo()  // 加载用户信息
    },
    mounted() {
      // if(this.$store.state.user.level === 1){
      //   if(this.$store.state.user.id === 1){
      //     this.showOneLevel = false
      //   }else{
      //     this.showTwoLevel = false
      //   }
      // }else if(this.$store.state.user.level === 2){
      //     this.showThreeLevel = false
      // }else if(this.$store.state.user.level === 3){
      //     this.showFourLevel = false
      // }else if(this.$store.state.user.level === 4){
      //     this.showFiveLevel = false
      // }else if(this.$store.state.user.level === 5){
      //     this.showSixLevel = false
      //     this.searchForm.sixUserId = this.$store.state.user.id
      // }
    },
    computed: {
  
    },
  
    methods: {
      /** 获取用户列表 */
      getUserListInfo(){
        userListPageAll().then((res) =>{
          if(res.code === 0 && res.data.length > 0){
            this.oneLevelUserInfoList = res.data
            console.log("全部用户信息为",res)
            if(this.oneLevelUserInfoList.length === 1){
              this.searchForm.userId = this.oneLevelUserInfoList[0].id
            }
          }
        })
      },
      //表格全选事件
      handleSelectionChange(){
        console.log("选中的数据",this.$refs.deviceTable.selection)
        this.exportList=this.$refs.deviceTable.selection
      },
      //搜索框用户选择改变
      selectChange(level){
        if(level === 1){
          this.searchForm.twoUserId = ''
          this.searchForm.threeUserId = ''
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showTwoLevel = true
          this.showThreeLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.userId
          for(var i=0;i<this.oneLevelUserInfoList.length;i++){
            if(this.paramId === this.oneLevelUserInfoList[i].id){
              if(this.oneLevelUserInfoList[i].subUsers.length > 0){
                this.twoLevelUserInfoList = this.oneLevelUserInfoList[i].subUsers
                this.showTwoLevel = false
              }
            }
          }
        }else if(level === 2){
          this.searchForm.threeUserId = ''
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showThreeLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.twoUserId
          for(var i=0;i<this.twoLevelUserInfoList.length;i++){
            if(this.paramId === this.twoLevelUserInfoList[i].id){
              if(this.twoLevelUserInfoList[i].subUsers.length > 0){
                this.threeLevelUserInfoList = this.twoLevelUserInfoList[i].subUsers
                this.showThreeLevel = false
              }
            }
          }
        }else if(level === 3){
          this.searchForm.fourUserId = ''
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showFourLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.threeUserId
          for(var i=0;i<this.threeLevelUserInfoList.length;i++){
            if(this.paramId === this.threeLevelUserInfoList[i].id){
              if(this.threeLevelUserInfoList[i].subUsers.length > 0){
                this.fourLevelUserInfoList = this.threeLevelUserInfoList[i].subUsers
                this.showFourLevel = false
              }
            }
          }
        }else if(level === 4){
          this.searchForm.fiveUserId = ''
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.showFiveLevel = true
          this.paramId = this.searchForm.fourUserId
          for(var i=0;i<this.fourLevelUserInfoList.length;i++){
            if(this.paramId === this.fourLevelUserInfoList[i].id){
              if(this.fourLevelUserInfoList[i].subUsers.length > 0){
                this.fiveLevelUserInfoList = this.fourLevelUserInfoList[i].subUsers
                this.showFiveLevel = false
              }
            }
          }
        }else if(level === 5){
          this.searchForm.sixUserId = ''
          this.showSixLevel = true
          this.paramId = this.searchForm.fiveUserId
          for(var i=0;i<this.fiveLevelUserInfoList.length;i++){
            if(this.paramId === this.fiveLevelUserInfoList[i].id){
              if(this.fiveLevelUserInfoList[i].subUsers.length > 0){
                this.sixLevelUserInfoList = this.fiveLevelUserInfoList[i].subUsers
                this.showSixLevel = false
              }
            }
          }
        }else{
          this.paramId = this.searchForm.sixUserId
        }
        userListSon({userId:this.paramId}).then((res) => {
          if(res.data != ''){
            if( level === 1 ){
              this.twoLevelUserListSearch=res.data
              this.showTwoLevel=false
            }else if( level === 2 ){
              this.threeLevelUserListSearch=res.data
              this.showThreeLevel=false
            }else if( level === 3 ){
              this.fourLevelUserListSearch=res.data
              this.showFourLevel=false
            }else if( level === 4 ){
              this.fiveLevelUserListSearch=res.data
              this.showFiveLevel=false
            }
  
          }
        }).catch((err) =>{
          console.log('## err ==> ', err)
        })
        //最后强制刷新
        this.$forceUpdate();
      },
      formatDate(cellValue) {
                if (cellValue == null || cellValue == "") return "";
                var date = new Date(cellValue*1000) 
                var year = date.getFullYear()
                var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
                var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() 
                var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() 
                var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() 
                var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
                return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
          },
      pagination() {
        // if (this.total > this.pageNum * this.pageSize) {
        //   this.pageNum += 1
        //   this.getListData()
        // }
        this.getListData()
      }, 
      queryByForm() {
        this.pageNum = 1;
        console.log("表单内容为",this.searchForm)
        this.getListData();
      },
      // 获取 冰柜 货柜列别数据
      getListData() {
        console.log(this.searchForm.dateTime)
        let bingdingUserId
        // 绑定要查找的用户id
        if(this.searchForm.sixUserId != ''){
          bingdingUserId=this.searchForm.sixUserId
        }else if(this.searchForm.fiveUserId != ''){
          bingdingUserId=this.searchForm.fiveUserId
        }else if(this.searchForm.fourUserId != ''){
          bingdingUserId=this.searchForm.fourUserId
        }else if(this.searchForm.threeUserId != ''){
          bingdingUserId=this.searchForm.threeUserId
        }else if(this.searchForm.twoUserId != ''){
          bingdingUserId=this.searchForm.twoUserId
        }else{
          bingdingUserId=this.searchForm.userId
        }
        if(this.searchForm.dateTime[0]){
          this.searchForm.startDate = this.searchForm.dateTime[0].slice(0,10)
        }else{
          this.$message.warning("请选择起止时间")
          return
        }
        if(this.searchForm.dateTime[1]){
          this.searchForm.endDate = this.searchForm.dateTime[1].slice(0,10)
        }else{
          this.$message.warning("请选择起止时间")
          return
        }
        const params = {
          userId:bingdingUserId,
          startDate:this.searchForm.startDate,
          endDate:this.searchForm.endDate,
          dimension:this.searchForm.dimension 
        }
        console.log("检索条件为",params)
        this.loading = true
        getKpiUser(params)
          .then((res) => {
            console.log('## devicesData ', res)
            this.devicesData = res.data
          })
          .catch((err) => {
            console.log('## list error ==>', err)
          })
          .finally(() => {
            this.loading = false
          })
        
      },
    }
  }
  </script>
  
  <style lang="scss">
  .app-container {
    background-color: #F3F3F3;
    width: 100%;
    height: calc(100vh - 85px);
    display: flex;
    flex-direction: column;
    padding: 1%;
}
.container{
    background-color: white;
    height: 100%;
    padding: 15px;
    border-radius: 8px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .radio {
    .el-radio__label {
      display: none;
    }
  }
  
  // ::v-deep .el-table .el-table__body td .cell:empty::after{
  //     content: "-";
  //   }
  .status-icon {
    width: 10px;
    height: 10px;
    display: inline-block;
    border-radius: 50%;
  }
  .c-grey {
    background: grey;
  }
  .c-green {
    background: green;
  }
  .c-red {
    background: red;
  }
  .c-yellow {
    background: yellow;
  }
  .device-long {
    white-space: nowrap;
  }
  .item-link {
    cursor: pointer;
    color: #409eff;
  }
  .page {
    display: flex;
    height: 80px;
    width: 100%;
    justify-content: center;
    align-items: center;
    box-shadow: 0px -2px 3px 0px rgba(0, 0, 0, 0.02);
    bottom: 10px;
    position: absolute;
}

.pageborder {
    margin-right: 10px;
    border: 1px solid #DCDFE6;
    width: 40px;
    height: 36px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #333;
    font-family: 'HarmonyOS_Sans_SC_Regular'
}
::v-deep .el-form-item--medium .el-form-item__label {
    font-family: 'HarmonyOS_Sans_SC_Regular';
}
  </style>